package ldk.xposed.dexreplace.utils

import android.util.Log
import java.io.DataOutputStream
import java.io.IOException

/**
 * Created by liangdengke on 2018/5/10.
 */
class ShellUtil {
    companion object {
        private val TAG = "ShellUtil"

        fun runShell(command: String, su: Boolean = true): Boolean{
            return try {
                val process =
                if (su){
                    val p = Runtime.getRuntime().exec("su");
                    val outputStream = DataOutputStream(p.outputStream);
                    outputStream.writeBytes(command + "\n")
                    outputStream.writeBytes("exit\n")
                    outputStream.flush()
                    outputStream.close()
                    p
                }else{
                    Runtime.getRuntime().exec(command)
                }
                val returnValue = process.waitFor()
                Log.d(TAG, "runShell: $command --> $returnValue")
                returnValue == 0
            }catch (e: IOException){
                Log.d(TAG, "runShell: $command error: ", e)
                false
            }
        }


        fun checkSu(): Boolean{
            return runShell("which su", false)
        }

        fun grant(packageName: String, permission: String){
            runShell("pm grant $packageName $permission")
        }

        fun resetCompile(packageName: String){
            runShell("cmd package compile --reset $packageName")
        }

        fun forceStop(packageName: String): Boolean{
            return runShell("am force-stop $packageName")
        }
    }
}